// pages/Dashboard/DashboardPanels.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from 'contexts/AuthContext';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { 
  CreateUser, 
  CreateTeam, 
  CreateWorkspace,
  RemoveCreditCard, 
  SetDefaultCreditCard, 
  CancelSubscription,
  CreateCustomerPortalSession,
  Clear,
  Logout
} from 'api/mutations';
import { 
  CustomerCards, 
  CustomerInvoices, 
  Me, 
  Workspaces, 
  TestDatabaseConnection,
  Customer 
} from 'api/queries';
import {
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Paper,
  Typography,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Select,
  FormControl,
  InputLabel,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  Dashboard as DashboardIcon,
  Group as TeamsIcon,
  Groups as UserTeamsIcon,
  People as UsersIcon,
  Folder as WorkspacesIcon,
  CreditCard as CardIcon,
  AccountBox as AccountIcon,
  Person as ProfileIcon,
  Payment as PlanIcon,
  Receipt as InvoiceIcon,
  Cable as TestIcon,
  PersonAdd as CreateUserIcon,
  GroupAdd as CreateTeamIcon,
  CreateNewFolder as CreateWorkspaceIcon,
  Refresh as RefreshIcon,
  CreditCardOff as RemoveCardIcon,
  Star as DefaultCardIcon,
  Cancel as CancelIcon,
  OpenInNew as PortalIcon,
  ExitToApp as LogoutIcon,
  Clear as ClearIcon
} from '@mui/icons-material';
import {
  paperSx,
  listItemSx,
  typographyHeaderSx,
  listContainerSx,
  menuSx,
  dialogSx,
  buttonPrimarySx,
  buttonSecondarySx,
  buttonDangerSx,
  formControlSx,
  alertSx
} from './sxobjects';

// QuickLeftPanel Component
export const QuickLeftPanel = ({ 
  user, 
  borderRadius = 1, 
  border = 1, 
  borderColor = 'primary.main', 
  planType = 'basic', 
  role = 'user' 
}) => {
  const navigate = useNavigate();
  
  const isAdmin = user && (user.role === "admin" || user.role === "superadmin");
  
  const navigationItems = [
    { icon: <DashboardIcon />, text: 'Dashboard Home', path: '/dashboard' },
    { icon: <TeamsIcon />, text: 'Teams', path: '/teams' },
    { icon: <UserTeamsIcon />, text: 'My Teams', path: '/user-teams' },
    { icon: <WorkspacesIcon />, text: 'Workspaces', path: '/workspaces' },
    { icon: <CardIcon />, text: 'Add Payment Method', path: '/card/add' },
    { icon: <AccountIcon />, text: 'Account Settings', path: '/account/edit' },
    { icon: <ProfileIcon />, text: 'Profile Settings', path: '/user/edit' },
    { icon: <PlanIcon />, text: 'Plans', path: '/plan' }
  ];
  
  // Add admin-only items
  if (isAdmin) {
    navigationItems.splice(3, 0, { 
      icon: <UsersIcon />, 
      text: 'Users', 
      path: '/users' 
    });
  }
  
  const handleNavigation = (path) => {
    navigate(path);
  };
  
  return (
    <Paper {...paperSx}>
      <Typography variant="h6" {...typographyHeaderSx}>
        Quick Navigation
      </Typography>
      <List {...listContainerSx}>
        {navigationItems.map((item, index) => (
          <ListItem 
            key={index}
            {...listItemSx}
            onClick={() => handleNavigation(item.path)}
          >
            <ListItemIcon>
              {item.icon}
            </ListItemIcon>
            <ListItemText primary={item.text} />
          </ListItem>
        ))}
      </List>
    </Paper>
  );
};

// QuickRightPanel Component
export const QuickRightPanel = ({ 
  user, 
  borderRadius = 1, 
  border = 1, 
  borderColor = 'primary.main', 
  planType = 'basic', 
  role = 'user' 
}) => {
  const queryClient = useQueryClient();
  const [anchorEl, setAnchorEl] = useState(null);
  const [menuType, setMenuType] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const [selectedValue, setSelectedValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [resultMessage, setResultMessage] = useState('');
  const [showResult, setShowResult] = useState(false);
  
  const isAdmin = user && (user.role === "admin" || user.role === "superadmin");
  
  // Queries
  const { refetch: refetchMe } = useQuery(["Me"], Me, { enabled: false });
  const { data: cardsData } = useQuery(["CustomerCards", user.accountId], CustomerCards);
  const { data: invoicesData } = useQuery(["CustomerInvoices", user.accountId], CustomerInvoices);
  const { data: workspacesData } = useQuery(["Workspaces"], Workspaces);
  
  // Mutations
  const createUserMutation = useMutation(CreateUser);
  const createTeamMutation = useMutation(CreateTeam);
  const createWorkspaceMutation = useMutation(CreateWorkspace);
  
  const handleMenuClick = (event, type) => {
    setAnchorEl(event.currentTarget);
    setMenuType(type);
  };
  
  const handleMenuClose = () => {
    setAnchorEl(null);
    setMenuType('');
  };
  
  const handleDialogOpen = (type) => {
    setDialogType(type);
    setDialogOpen(true);
    setShowResult(false);
    setResultMessage('');
    handleMenuClose();
  };
  
  const handleDialogClose = () => {
    setDialogOpen(false);
    setDialogType('');
    setSelectedValue('');
    setShowResult(false);
    setResultMessage('');
    setIsLoading(false);
  };
  
  const handleRefreshData = () => {
    refetchMe();
    queryClient.invalidateQueries();
  };
  
  const handleTestConnection = async () => {
    if (!selectedValue) return;
    
    setIsLoading(true);
    try {
      await TestDatabaseConnection(selectedValue);
      setResultMessage('Database connection successful!');
    } catch (error) {
      setResultMessage('Database connection failed: ' + (error.message || 'Unknown error'));
    }
    setIsLoading(false);
    setShowResult(true);
  };
  
  const actionItems = [
    { icon: <CardIcon />, text: 'View Payment Methods', action: 'dialog', type: 'payment' },
    { icon: <InvoiceIcon />, text: 'View Payment History', action: 'dialog', type: 'invoices' },
    { icon: <TestIcon />, text: 'Test Database Connection', action: 'dialog', type: 'test' },
    { icon: <RefreshIcon />, text: 'Refresh Account Data', action: 'direct', type: 'refresh' }
  ];
  
  // Add admin-only items
  if (isAdmin) {
    actionItems.splice(3, 0, 
      { icon: <CreateUserIcon />, text: 'Create New User', action: 'menu', type: 'createUser' },
      { icon: <CreateTeamIcon />, text: 'Create New Team', action: 'menu', type: 'createTeam' },
      { icon: <CreateWorkspaceIcon />, text: 'Create New Workspace', action: 'menu', type: 'createWorkspace' }
    );
  }
  
  const handleItemClick = (item, e) => {
    if (item.action === 'direct' && item.type === 'refresh') {
      handleRefreshData();
    } else if (item.action === 'menu') {
      handleMenuClick(e, item.type);
    } else if (item.action === 'dialog') {
      handleDialogOpen(item.type);
    }
  };
  
  const renderDialogContent = () => {
    if (showResult) {
      return (
        <Alert {...alertSx} severity={resultMessage.includes('successful') ? 'success' : 'error'}>
          {resultMessage}
        </Alert>
      );
    }
    
    if (isLoading) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <CircularProgress size={24} />
          <Typography>Testing connection...</Typography>
        </div>
      );
    }
    
    switch (dialogType) {
      case 'payment':
        return (
          <div>
            <Typography variant="h6" gutterBottom>Payment Methods</Typography>
            {cardsData?.data?.map((card) => (
              <Typography key={card.id} variant="body2" paragraph>
                {card.brand} **** **** **** {card.last4}
                {card.default_source && ' (Default)'}
              </Typography>
            )) || <Typography>No payment methods found</Typography>}
          </div>
        );
      case 'invoices':
        return (
          <div>
            <Typography variant="h6" gutterBottom>Payment History</Typography>
            {invoicesData?.data?.slice(0, 5).map((invoice) => (
              <Typography key={invoice.id} variant="body2" paragraph>
                ${(invoice.amount_paid / 100).toFixed(2)} - {new Date(invoice.created * 1000).toLocaleDateString()}
              </Typography>
            )) || <Typography>No payment history found</Typography>}
          </div>
        );
      case 'test':
        return (
          <FormControl {...formControlSx}>
            <InputLabel>Select Workspace</InputLabel>
            <Select
              value={selectedValue}
              onChange={(e) => setSelectedValue(e.target.value)}
              label="Select Workspace"
            >
              {workspacesData?.data?.map((workspace) => (
                <MenuItem key={workspace.id} value={workspace.id}>
                  {workspace.name}
                </MenuItem>
              )) || []}
            </Select>
          </FormControl>
        );
      default:
        return null;
    }
  };
  
  const getDialogTitle = () => {
    switch (dialogType) {
      case 'payment':
        return 'Payment Methods';
      case 'invoices':
        return 'Payment History';
      case 'test':
        return 'Test Database Connection';
      default:
        return 'Quick Action';
    }
  };
  
  const getDialogActions = () => {
    if (showResult || dialogType === 'payment' || dialogType === 'invoices') {
      return (
        <Button {...buttonSecondarySx} onClick={handleDialogClose}>Close</Button>
      );
    }
    
    if (dialogType === 'test') {
      return (
        <>
          <Button {...buttonSecondarySx} onClick={handleDialogClose}>Cancel</Button>
          <Button 
            {...buttonPrimarySx}
            onClick={handleTestConnection} 
            disabled={!selectedValue || isLoading}
          >
            Test Connection
          </Button>
        </>
      );
    }
    
    return <Button {...buttonSecondarySx} onClick={handleDialogClose}>Close</Button>;
  };
  
  return (
    <Paper {...paperSx}>
      <Typography variant="h6" {...typographyHeaderSx}>
        Quick Actions
      </Typography>
      <List {...listContainerSx}>
        {actionItems.map((item, index) => (
          <ListItem 
            key={index}
            {...listItemSx}
            onClick={(e) => handleItemClick(item, e)}
          >
            <ListItemIcon>
              {item.icon}
            </ListItemIcon>
            <ListItemText primary={item.text} />
          </ListItem>
        ))}
      </List>
      
      {/* Menu for create actions */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
        {...menuSx}
      >
        {menuType === 'createUser' && (
          <MenuItem onClick={() => { window.location.href = '/create-user'; handleMenuClose(); }}>
            Open User Form
          </MenuItem>
        )}
        {menuType === 'createTeam' && (
          <MenuItem onClick={() => { window.location.href = '/teams'; handleMenuClose(); }}>
            Open Team Form
          </MenuItem>
        )}
        {menuType === 'createWorkspace' && (
          <MenuItem onClick={() => { window.location.href = '/workspaces/create'; handleMenuClose(); }}>
            Open Workspace Form
          </MenuItem>
        )}
      </Menu>
      
      {/* Dialog for view/test actions */}
      <Dialog 
        open={dialogOpen} 
        onClose={handleDialogClose} 
        maxWidth="sm" 
        fullWidth
        {...dialogSx}
      >
        <DialogTitle>{getDialogTitle()}</DialogTitle>
        <DialogContent>
          {renderDialogContent()}
        </DialogContent>
        <DialogActions>
          {getDialogActions()}
        </DialogActions>
      </Dialog>
    </Paper>
  );
};

// QuickActionsPanel Component
export const QuickActionsPanel = ({ 
  user, 
  borderRadius = 1, 
  border = 1, 
  borderColor = 'primary.main', 
  planType = 'basic', 
  role = 'user' 
}) => {
  const { refetch } = useAuth();
  const queryClient = useQueryClient();
  const [anchorEl, setAnchorEl] = useState(null);
  const [menuType, setMenuType] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const [selectedValue, setSelectedValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [resultMessage, setResultMessage] = useState('');
  const [showResult, setShowResult] = useState(false);
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [selectedCardId, setSelectedCardId] = useState('');
  
  // Queries
  const { data: cardsData } = useQuery(["CustomerCards", user.accountId], CustomerCards);
  const { data: customerData } = useQuery(["Customer", user.accountId], Customer);
  
  // Mutations
  const removeCardMutation = useMutation(RemoveCreditCard, {
    onSuccess: () => {
      queryClient.invalidateQueries(["CustomerCards", user.accountId]);
      setResultMessage('Payment method removed successfully!');
      setShowResult(true);
      setIsLoading(false);
    },
    onError: (error) => {
      setResultMessage('Failed to remove payment method: ' + (error.message || 'Unknown error'));
      setShowResult(true);
      setIsLoading(false);
    }
  });
  
  const setDefaultCardMutation = useMutation(SetDefaultCreditCard, {
    onSuccess: () => {
      queryClient.invalidateQueries(["Customer", user.accountId]);
      setResultMessage('Default payment method updated successfully!');
      setShowResult(true);
      setIsLoading(false);
    },
    onError: (error) => {
      setResultMessage('Failed to update default payment method: ' + (error.message || 'Unknown error'));
      setShowResult(true);
      setIsLoading(false);
    }
  });
  
  const cancelSubscriptionMutation = useMutation(CancelSubscription, {
    onSuccess: () => {
      queryClient.invalidateQueries(["Customer", user.accountId]);
      setResultMessage('Subscription cancelled successfully!');
      setShowResult(true);
      setIsLoading(false);
    },
    onError: (error) => {
      setResultMessage('Failed to cancel subscription: ' + (error.message || 'Unknown error'));
      setShowResult(true);
      setIsLoading(false);
    }
  });
  
  const customerPortalMutation = useMutation(CreateCustomerPortalSession, {
    onSuccess: (response) => {
      window.location.href = response.data.redirect_url;
    }
  });
  
  const handleMenuClick = (event, type) => {
    setAnchorEl(event.currentTarget);
    setMenuType(type);
  };
  
  const handleMenuClose = () => {
    setAnchorEl(null);
    setMenuType('');
  };
  
  const handleCardMenuItemClick = (cardId, action) => {
    setSelectedCardId(cardId);
    setDialogType(action);
    setConfirmDialogOpen(true);
    handleMenuClose();
  };
  
  const handleDialogOpen = (type) => {
    setDialogType(type);
    setDialogOpen(true);
    setShowResult(false);
    setResultMessage('');
  };
  
  const handleDialogClose = () => {
    setDialogOpen(false);
    setConfirmDialogOpen(false);
    setDialogType('');
    setSelectedValue('');
    setSelectedCardId('');
    setShowResult(false);
    setResultMessage('');
    setIsLoading(false);
  };
  
  const handleConfirmCardAction = async () => {
    setConfirmDialogOpen(false);
    setIsLoading(true);
    
    if (dialogType === 'removeCard') {
      removeCardMutation.mutate({ cardId: selectedCardId });
    } else if (dialogType === 'defaultCard') {
      setDefaultCardMutation.mutate({ cardId: selectedCardId });
    }
  };
  
  const handleCancelSubscription = async () => {
    if (!selectedValue) return;
    
    setIsLoading(true);
    cancelSubscriptionMutation.mutate({ subscriptionId: selectedValue });
  };
  
  const handleCustomerPortal = () => {
    customerPortalMutation.mutate();
  };
  
  const handleClearAndLogout = async () => {
    await Clear();
    await Logout();
    await refetch();
    window.location.href = "/auth/login";
  };
  
  const actionItems = [
    { icon: <RemoveCardIcon />, text: 'Remove Payment Method', action: 'cardMenu', type: 'removeCard' },
    { icon: <DefaultCardIcon />, text: 'Set Default Payment Method', action: 'cardMenu', type: 'defaultCard' },
    { icon: <CancelIcon />, text: 'Cancel Subscription', action: 'dialog', type: 'cancelSubscription' },
    { icon: <PortalIcon />, text: 'Open Customer Portal', action: 'direct', type: 'portal' },
    { icon: <ClearIcon />, text: 'Clear Cache', action: 'direct', type: 'clear' },
    { icon: <LogoutIcon />, text: 'Logout', action: 'direct', type: 'logout' }
  ];
  
  const handleItemClick = (item, e) => {
    if (item.action === 'direct') {
      switch (item.type) {
        case 'portal':
          handleCustomerPortal();
          break;
        case 'clear':
          Clear();
          break;
        case 'logout':
          handleClearAndLogout();
          break;
        default:
          break;
      }
    } else if (item.action === 'cardMenu') {
      handleMenuClick(e, item.type);
    } else if (item.action === 'dialog') {
      handleDialogOpen(item.type);
    }
  };
  
  const renderDialogContent = () => {
    if (showResult) {
      return (
        <Alert {...alertSx} severity={resultMessage.includes('successfully') ? 'success' : 'error'}>
          {resultMessage}
        </Alert>
      );
    }
    
    if (isLoading) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <CircularProgress size={24} />
          <Typography>Processing...</Typography>
        </div>
      );
    }
    
    switch (dialogType) {
      case 'cancelSubscription':
        return (
          <FormControl {...formControlSx}>
            <InputLabel>Select Subscription</InputLabel>
            <Select
              value={selectedValue}
              onChange={(e) => setSelectedValue(e.target.value)}
              label="Select Subscription"
            >
              {customerData?.data?.subscriptions?.data?.map((subscription) => (
                <MenuItem key={subscription.id} value={subscription.id}>
                  {subscription.plan?.name || 'Current Subscription'} - ${(subscription.plan?.amount / 100).toFixed(2)}
                </MenuItem>
              )) || []}
            </Select>
          </FormControl>
        );
      default:
        return null;
    }
  };
  
  const getDialogTitle = () => {
    switch (dialogType) {
      case 'removeCard':
        return 'Remove Payment Method';
      case 'defaultCard':
        return 'Set Default Payment Method';
      case 'cancelSubscription':
        return 'Cancel Subscription';
      default:
        return 'Confirm Action';
    }
  };
  
  const getDialogActions = () => {
    if (showResult) {
      return <Button {...buttonSecondarySx} onClick={handleDialogClose}>Close</Button>;
    }
    
    if (dialogType === 'cancelSubscription') {
      return (
        <>
          <Button {...buttonSecondarySx} onClick={handleDialogClose}>Cancel</Button>
          <Button 
            {...buttonDangerSx}
            onClick={handleCancelSubscription} 
            disabled={!selectedValue || isLoading}
          >
            Cancel Subscription
          </Button>
        </>
      );
    }
    
    return <Button {...buttonSecondarySx} onClick={handleDialogClose}>Close</Button>;
  };
  
  return (
    <Paper {...paperSx}>
      <Typography variant="h6" {...typographyHeaderSx}>
        Dashboard Actions
      </Typography>
      <List {...listContainerSx}>
        {actionItems.map((item, index) => (
          <ListItem 
            key={index}
            {...listItemSx}
            onClick={(e) => handleItemClick(item, e)}
          >
            <ListItemIcon>
              {item.icon}
            </ListItemIcon>
            <ListItemText primary={item.text} />
          </ListItem>
        ))}
      </List>
      
      {/* Card Actions Menu */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
        {...menuSx}
      >
        {(menuType === 'removeCard' || menuType === 'defaultCard') && 
          cardsData?.data?.map((card) => (
            <MenuItem 
              key={card.id} 
              onClick={() => handleCardMenuItemClick(card.id, menuType)}
            >
              {card.brand} **** **** **** {card.last4}
              {card.default_source && ' (Current Default)'}
            </MenuItem>
          ))
        }
      </Menu>
      
      {/* Card Action Confirmation Dialog */}
      <Dialog 
        open={confirmDialogOpen} 
        onClose={handleDialogClose}
        {...dialogSx}
      >
        <DialogTitle>{getDialogTitle()}</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to {dialogType === 'removeCard' ? 'remove' : 'set as default'} this payment method?
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button {...buttonSecondarySx} onClick={handleDialogClose}>Cancel</Button>
          <Button 
            {...(dialogType === 'removeCard' ? buttonDangerSx : buttonPrimarySx)}
            onClick={handleConfirmCardAction}
          >
            Confirm
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Other Actions Dialog */}
      <Dialog 
        open={dialogOpen} 
        onClose={handleDialogClose} 
        maxWidth="sm" 
        fullWidth
        {...dialogSx}
      >
        <DialogTitle>{getDialogTitle()}</DialogTitle>
        <DialogContent>
          {renderDialogContent()}
        </DialogContent>
        <DialogActions>
          {getDialogActions()}
        </DialogActions>
      </Dialog>
    </Paper>
  );
};